/**   
 * @Title: LotteryRecordWinningAct.java 
 * @Package com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord 
 * @Description: 购彩记录,最近中奖
 * @author: City Jiangsy@500wan.com   
 * @date: 2012-1-10 下午4:28:36  
 * Copyright: (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.LotteryRecordInfo;
import com.esun.model.UserInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.rabbit2.communicaters.lotteryrecord.GetLotteryRecordListCommunicater;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.PullToRefreshListView;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.PullToRefreshListView.OnRefreshListener;
import com.esun.ui.R;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/**
 * @ClassName: LotteryRecordWinningAct
 * @Description: 购彩记录,最近中奖
 * @author: City Jiangsy@500wan.com
 * @date: 2012-1-10 下午4:28:36
 * 
 */
public class LotteryRecordWinningAct extends Activity implements OnScrollListener, OnItemClickListener, OnRefreshListener {
	private PullToRefreshListView listViewLotteryRecordTotal; // 全部购彩记录列表
	private ArrayList<Hashtable<String, String>> alItem; // 列表数据存储
	private ArrayList<View> itemViewList;
	private LotteryRecordListAdapterModify adapter;
	private LinearLayout linearFooter; // 列表底部加载布局
	private LinearLayout linearNoMore;
	private LinearLayout linearBottom;
	private ProgressDialog progressDialog;
	public static Handler handlerGetTotalLotteryRecord;
	private GetLotteryRecordListCommunicater totalLotteryRecordCommunicater;
	private String serverMessage; // 服务器返回信息
	private int refreshORBottom = 2; // state=1刷新 state=2到底部
	private int pageno = 1;
	private Intent intent;
	private Bundle bundle;
	private LinearLayout linearNoMoreRecord;
	private boolean isShow = true;
	private boolean isRunning;// 是否正在通信
	private boolean isFirstLoad = true; // 是否是第一次加载
	private boolean isNoMoreRecord = true; // 是否还有记录
	private boolean isBottomChanged = true;

	private final int GET_LOTTERYRECORD_SUCCEED = 1001; // 与服务器通信成功、失败
	private final int GET_LOTTERYRECORD_FAIL = 1002;
	private final String LOTID = "1"; // 通信所需参数 ,0：未结 ;1：最近中奖; -1：全部

	private final int FOOTER_VIEW_TAG = 10000;
	private final int FOOTER_VIEW_TAG2 = 20000;
	private final int FOOTER_VIEW_TAG3 = 30000;
	private LotteryKindJudgment lotterykindjudgment;
	/** 2012-2-7 city add 调整无记录时提示语 */
	private TextView tvNoRecord;
	private String strNoRecord = "最近一个月没有中奖记录";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lotteryrecord_total_act);
		lotterykindjudgment = new LotteryKindJudgment();
		initUI();
		initHandler();

	}

	@Override
	protected void onPause() {
		super.onPause();
		isShow = false;
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {
		super.onResume();
		isShow = true;
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());
		if (UserInfo.getUserInfo().isRebuy()) {
			getParent().finish();
		}
	}

	// 初始化
	public void initUI() {

		isRunning = false;

		progressDialog = ViewerUtil.showProgressDialog(LotteryRecordWinningAct.this, getResources().getString(R.string.loading_text));
		progressDialog.show();

		listViewLotteryRecordTotal = (PullToRefreshListView) findViewById(R.id.lotteryrecordtotalact_listview);
		linearFooter = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryinfoact_linear_footer, null);
		linearNoMore = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryrecordlist_act_linear_nomore, null);
		linearBottom = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.listview_bottom_view, null);
		linearFooter.setTag(FOOTER_VIEW_TAG);
		linearNoMore.setTag(FOOTER_VIEW_TAG2);
		linearBottom.setTag(FOOTER_VIEW_TAG3);

		alItem = new ArrayList<Hashtable<String, String>>();
		itemViewList = new ArrayList<View>();
		adapter = new LotteryRecordListAdapterModify(LotteryRecordWinningAct.this, alItem, itemViewList);
		listViewLotteryRecordTotal.addFooterView(linearFooter);// 增加底部状态条
		listViewLotteryRecordTotal.setAdapter(adapter);
		listViewLotteryRecordTotal.removeFooterView(linearFooter);
		linearNoMoreRecord = (LinearLayout) findViewById(R.id.lotteryrecord_totalact_linear_noRecord);

		listViewLotteryRecordTotal.setOnItemClickListener(this);
		listViewLotteryRecordTotal.setOnRefreshListener(this);
		listViewLotteryRecordTotal.setOnScrollListener(this);

		tvNoRecord = (TextView) findViewById(R.id.lotteryrecord_totalact_tv_norecord);
		tvNoRecord.setText(strNoRecord);

	}

	// 与服务器通信线程
	public void getTotalLotteryRecordThread() {
		new Thread() {
			@Override
			public void run() {
				totalLotteryRecordCommunicater = new GetLotteryRecordListCommunicater();
				Message msg = handlerGetTotalLotteryRecord.obtainMessage();
				try {
					boolean isSucceed = totalLotteryRecordCommunicater.isGetLotteryRecord(LOTID, String.valueOf(pageno));
					serverMessage = totalLotteryRecordCommunicater.getServerMsg();
					EDebug.o(this, totalLotteryRecordCommunicater.getErrorCode());
					if (isSucceed) {
						msg.what = GET_LOTTERYRECORD_SUCCEED;
					} else {
						msg.what = GET_LOTTERYRECORD_FAIL;
					}
					handlerGetTotalLotteryRecord.sendMessage(msg);
				} catch (Exception e) {
					msg.what = Config.CONNECTION_FAIL;
					handlerGetTotalLotteryRecord.sendMessage(msg);
				}
			}
		}.start();
	}

	// 消息处理
	public void initHandler() {
		handlerGetTotalLotteryRecord = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				listViewLotteryRecordTotal.removeFooterView(linearBottom);
				switch (msg.what) {
				case GET_LOTTERYRECORD_SUCCEED:

					pageno++;
					communicateSucceed(totalLotteryRecordCommunicater.getLotteryRecordList());
					itemViewList.clear();
					adapter.notifyDataSetChanged();
					if (totalLotteryRecordCommunicater.getLotteryRecordList().size() < 10) {
						isNoMoreRecord = false;
						listViewLotteryRecordTotal.addFooterView(linearNoMore);
					}
					lengthAutoAdapter();
					endProcess();
					break;

				case GET_LOTTERYRECORD_FAIL:

					// 无更多记录
					isBottomChanged = false;
					if (totalLotteryRecordCommunicater.getState() == 202) {
						isNoMoreRecord = false;
						if (pageno == 1) {
							// alItem.clear();
							linearNoMoreRecord.setVisibility(View.VISIBLE);
						} else {
							listViewLotteryRecordTotal.addFooterView(linearNoMore);
						}
					} else {
						// 通讯失败
						if (isShow) {
						  
							//ViewerUtil.showTipDialog(LotteryRecordWinningAct.this, serverMessage, false);
							Toast.makeText(LotteryRecordWinningAct.this, serverMessage, Toast.LENGTH_SHORT).show();
						}
					}
					lengthAutoAdapter();
					endProcess();

					break;

				case Config.CONNECTION_FAIL:

					if (isShow) {
					
					  ViewerUtil.showTipDialog(LotteryRecordWinningAct.this, Language.STR_CONNECTIONFAIL, false);
					  Toast.makeText(LotteryRecordWinningAct.this, Language.STR_CONNECTIONFAIL, Toast.LENGTH_SHORT).show();
					}
					isBottomChanged = false;
					lengthAutoAdapter();
					endProcess();

					break;

				case com.esun.config.Config.DO_REFRESH:
					EDebug.o(this, "do refresh");
					if (!isRunning) {
						listViewLotteryRecordTotal.prepareForRefresh();
						listViewLotteryRecordTotal.onRefresh();
						progressDialog.show();
					}
					LotteryRecordAgp.isCanClick = true;

					break;

				default:
					break;
				}
			}
		};
	}

	private void endProcess() {
		if (refreshORBottom == 1) {
			listViewLotteryRecordTotal.onRefreshComplete();
		} else {
			listViewLotteryRecordTotal.removeFooterView(linearFooter);
		}
		if (progressDialog != null) {
			progressDialog.cancel();
		}
		isRunning = false;
	}

	// 通讯成功处理
	public void communicateSucceed(ArrayList<LotteryRecordInfo> list) {

		ArrayList<Hashtable<String, String>> alItemTemp = new ArrayList<Hashtable<String, String>>();

		for (int i = 0; i < list.size(); i++) {

			Hashtable<String, String> map = new Hashtable<String, String>();
			map.put(Key.KEY_ISTITLE, "no");
			// 显示参数
			map.put(Key.KEY_ADDDATE, list.get(i).getLotterDate());
			map.put(Key.KEY_ADDTIME, list.get(i).getLotterTime());
			map.put(Key.KEY_EXPECT, list.get(i).getExcept());
			map.put(Key.KEY_PAYMONEY, list.get(i).getPayMoney());
			map.put(Key.KEY_PLAYNAME, list.get(i).getPlayName());
			map.put(Key.KEY_GETMONEY, list.get(i).getGetMoney());
			map.put(Key.KEY_STATE, list.get(i).getLotteryState());
			map.put(Key.KEY_ISSUC, list.get(i).getIssuc());
			map.put(Key.KEY_LOTNAME, list.get(i).getLotName());
			// 取详情传递参数
			map.put(Key.KEY_LOTID, list.get(i).getLotID());
			map.put(Key.KEY_UID, list.get(i).getUID());
			map.put(Key.KEY_PROID, list.get(i).getProID());
			map.put(Key.KEY_ID, list.get(i).getID());
			map.put(Key.KEY_PLAYID, list.get(i).getPlayId());
			map.put(Key.KEY_FAQIREN, list.get(i).getFauserName());

			alItemTemp.add(map);
			childCount++;
		}
		if (refreshORBottom == 1) {
			alItem.clear();
		}
		alItem.addAll(alItemTemp);
	}

	// 到底事件
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if ((firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0)) {
			if (isNoMoreRecord) {
				if (isFirstLoad) {
					listViewLotteryRecordTotal.prepareForRefresh();
					listViewLotteryRecordTotal.onRefresh();
					isFirstLoad = false;
				} else {
					if (!isRunning && isBottomChanged) {
						isRunning = true;
						listViewLotteryRecordTotal.addFooterView(linearFooter);
						refreshORBottom = 2;
						getTotalLotteryRecordThread();
					}
				}
			}
		} else {
			isBottomChanged = true;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	// 判断是否是胆拖，因暂不支持不显示详情
	public static boolean isDanTuo(String str) {
		int[] dantuo = { 123, 135, 137, 141, 142, 143, 172, 175, 176, 177, 178, 179, 261, 264, 265, 266, 267, 268, 278, 279, 280 };
		boolean b = false;
		for (int i = 0; i < dantuo.length; i++) {
			if (str.equals(String.valueOf(dantuo[i]))) {
				b = true;
				break;
			}
		}
		return b;
	}

	/**
	 * ,123,135,137,141,142,143,172,175,176,177,178,179,261,264,265,266,267,268, 278,279,280,
	 */

	// 将menu键点击事件返回给父activity处理
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onRefresh() {
		if (!isRunning) {
			pageno = 1;
			isRunning = true;
			isNoMoreRecord = true;
			refreshORBottom = 1;
			groupCount = 0;
			childCount = 0;
			itemViewList.clear();
			linearNoMoreRecord.setVisibility(View.GONE);
			if (listViewLotteryRecordTotal.getFooterViewsCount() != 0) {
				listViewLotteryRecordTotal.removeFooterView(linearNoMore);
			}
			getTotalLotteryRecordThread();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		if (arg1.getTag() != null
				&& (Integer.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG || Integer.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG2 || Integer.parseInt(String.valueOf(arg1
						.getTag())) == FOOTER_VIEW_TAG3)) {
			return;
		} else {
			if (alItem.get(arg2 - 1).get("istitle").equals("no")) {
				String getkindid = alItem.get(arg2 - 1).get(Key.KEY_LOTID);
				int tag = 2;// 彩种判断方法参数，购彩记录处传2
				if (arg2 <= alItem.size() && lotterykindjudgment.lotterykindsjudgment(Integer.parseInt(getkindid), tag)) {
					Hashtable<String, String> strItem = alItem.get(arg2 - 1);
					String tempStrPlayId = strItem.get("playid");
					if (isDanTuo(tempStrPlayId)) {
						Toast.makeText(LotteryRecordWinningAct.this, "暂不支持胆拖", Toast.LENGTH_SHORT).show();
					} else {
						intent = new Intent();
						bundle = new Bundle();
						bundle.putString(Key.KEY_LOTID, strItem.get("lotid"));
						bundle.putString(Key.KEY_ID, strItem.get("id"));
						bundle.putString(Key.KEY_UID, strItem.get("uid"));
						bundle.putString(Key.KEY_PROID, strItem.get("proid"));
						bundle.putString(Key.KEY_EXPECT, strItem.get("expect"));
						bundle.putString(Key.KEY_FAQIREN, strItem.get("faqiren"));
						bundle.putString(Key.KEY_GETMONEY, strItem.get("getmoney"));
						bundle.putString(Key.KEY_PLAYID, tempStrPlayId);
						bundle.putString(Key.KEY_LOTNAME, strItem.get("lotname"));
						intent.putExtras(bundle);
						if (strItem.get("lotid").equals(Config.JINGCAIZUQIU)) {
							intent.setClass(LotteryRecordWinningAct.this, LotteryRecordDetailFootballAct.class);
						} else if (strItem.get("lotid").equals(Config.SHENGFUCAI) || strItem.get("lotid").equals(Config.RENXUANJIU)) {
							intent.setClass(LotteryRecordWinningAct.this, ShengfurenjiuRecordDetailAct.class);
						} else if (strItem.get("lotid").equals(Config.BEIJINGZUQIUDANCHANG) || strItem.get("lotid").equals(Config.PLAYID_BEIJINGZUQIUDANCHANG_SHENGPINGFU)) {
							intent.setClass(LotteryRecordWinningAct.this, BeidanRecordDetailAct.class);
						} else if (strItem.get("lotid").equals(Config.JINGCAILANQIU)) {
							intent.setClass(LotteryRecordWinningAct.this, LotteryRecordDetailBasketballAct.class);
						} else {
							intent.setClass(LotteryRecordWinningAct.this, LotteryRecordDetailAct.class);
						}
						startActivity(intent);
					}
				} else {
					Toast.makeText(LotteryRecordWinningAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	private int groupCount = 0;
	private int childCount = 0;

	private void lengthAutoAdapter() {
		int itemHeight = 30 * groupCount + childCount * (90 + 1);

		// 判断是否需要加入额外item
		if (itemHeight < listViewLotteryRecordTotal.getHeight()) {
			LinearLayout linearChild = new LinearLayout(this);
			int bheight = 0;
			linearChild.setBackgroundColor(Color.WHITE);
			if (listViewLotteryRecordTotal.getFooterViewsCount() > 0) {
				bheight = listViewLotteryRecordTotal.getHeight() - itemHeight - 30;
			} else {
				bheight = listViewLotteryRecordTotal.getHeight() - itemHeight;
			}
			linearBottom.addView(linearChild);
			for (int i = 0; i < linearBottom.getChildCount(); i++) {
				linearBottom.getChildAt(i).getLayoutParams().height = bheight;
				linearBottom.getChildAt(i).getLayoutParams().width = LayoutParams.FILL_PARENT;
			}
			linearChild.setBackgroundColor(Color.WHITE);
			listViewLotteryRecordTotal.addFooterView(linearBottom);
		}
	}
}
